// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.internal.job;

import org.apache.tapestry.ioc.OrderedConfiguration;
import org.apache.tapestry.ioc.annotations.Inject;
import org.apache.tapestry.ioc.annotations.InjectService;
import org.apache.tapestry.services.ApplicationInitializer;
import org.apache.tapestry.services.ApplicationInitializerFilter;
import org.apache.tapestry.services.Context;
import org.hibernate.SessionFactory;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;

/**
 * 定时器实现的module.
 * @author Jun Tsai
 * @version $Revision: 61 $
 * @since 0.0.3
 */
public class SchedulerJobModule {
	/** Job 中使用到的hibernate 的source **/
	public static final Object HIBERNATE_SESSION_SOURCE = "job-hibernate-session-source";
	
    /**
     * 构建检查在线人数的服务类
     * @param sessionFactory hibernate Session Factory
     * @return check online job detail
     * @see lichen.hibernate.HibernateSessionFactory#getSessionFactory()
     */
    public JobDetail buildCheckOnlineJob(@Inject SessionFactory sessionFactory){
    	JobDetail jobDetail = new JobDetail("check-online-job", "lichen", CheckOnline.class);
		jobDetail.getJobDataMap().put(HIBERNATE_SESSION_SOURCE,sessionFactory);
		return jobDetail;
    }
    /**
     * 初始化所有的job项目
     * @param configuration configuration
     * @param factory scheduler factory
     * @param job jobDetail
     */
    public void contributeApplicationInitializer(
			OrderedConfiguration<ApplicationInitializerFilter> configuration,@Inject
			final SchedulerFactory factory,@InjectService("checkOnlineJob")
			final JobDetail job){
    	ApplicationInitializerFilter initCheckOnlinJob = new ApplicationInitializerFilter() {
			public void initializeApplication(Context context,
					ApplicationInitializer initializer) {
				Scheduler sched;
				try {
					sched = factory.getScheduler();
					sched.start();
					Trigger trigger = TriggerUtils.makeSecondlyTrigger(10);  
					trigger.setName("checkonlinejob-trigger");
					sched.scheduleJob(job, trigger);
				} catch (SchedulerException e) {
					e.printStackTrace();
				}
				initializer.initializeApplication(context);
			}
		};
		configuration.add("init-checkonline-job", initCheckOnlinJob);
    }

}
